package controllers

import (
	//"bufio"
	"fmt"
	"log"
	m "xwaf_admin/models"

	"github.com/tidwall/gjson"
)

type RwlController struct {
	CommonController
}

//列表
func (this *RwlController) List() {
	appname := this.GetString("appname")
	id, _ := this.GetInt64("id")
	datas, count := m.GetRwlList(appname, id)
	this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &datas}
	//this.Data["json"] = &datas
	this.ServeJSON()
}

//添加
func (this *RwlController) Add() {
	u := m.Limitwhite{}
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
	log.Println(string(this.Ctx.Input.RequestBody))
	appname := this.GetString("appname")
	if gp.Get("ruletype").Exists() {
		u.Appname = appname
		u.Ruletype = gp.Get("ruletype").String()
		u.Ruleitem = gp.Get("ruleitem").String()
		u.Remarks = gp.Get("remarks").String()
		id, err := m.AddRwl(&u)
		if err == nil && id > 0 {
			log.Printf("[INFO] Add success")
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] Add Fail:%s", err)
			this.Ctx.WriteString(`{"code":-1,"msg":"error"}`)
		}
		//this.Ctx.WriteString(`{"code":0,"msg":"test"}`)
	} else {
		this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "bodyParseFail"}
		this.ServeJSON()
	}
}

// //删除
func (this *RwlController) Del() {
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	Id, _ := this.GetInt64("id")
	appname := this.GetString("appname")
	respid, err := m.DelByRwlId(Id, appname)
	if err == nil && respid > 0 {
		log.Printf("[INFO] Delsuccess")
		this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
	} else {
		log.Printf("[ERROR] Del Error:%s\n", err.Error())
		this.Ctx.WriteString(`{"code":-1,"msg":"Error"}`)
	}
}

//
func (this *RwlController) Edit() {
	id := this.GetString("id")
	appname := this.GetString("appname")
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)

	if gp.Get("name").Exists() {
		name := gp.Get("name").String()
		value := gp.Get("value").String()
		if appname == "" {
			appname = gp.Get("appname").String()
		}
		_, err := m.EditRwl(id, appname, name, value)
		if err == nil {
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] Edit reqlimitRule Fail:%s\n", err)
			this.Ctx.WriteString(fmt.Sprintf(`{"code":-1,"msg":"%s"}`, err.Error()))
		}
	} else {
		this.Ctx.WriteString(`{"code":-1,"msg":"bodyParseFail"}`)
	}
}
